import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

sns.set(style="white", font_scale=1.5)
plt.rcParams['font.sans-serif'] = "Simsun"  # 支持中文字体
# Excel文件路径
excel_file = 'D:\文档\DLMU\HLJU-MOPSO实验结果.xlsx'

# 使用pandas读取Excel文件
xls = pd.ExcelFile(excel_file)
sheet_names = xls.sheet_names

# 初始化数据列表
data = []

# 遍历所有 Sheet，读取数据
for sheet_name in sheet_names:
    df = pd.read_excel(excel_file, sheet_name=sheet_name)
    if all(df.columns.isnull()):  # 如果所有列名都为空，跳过
        continue
    df = df.dropna(how="all")  # 去除完全空的行
    if "迭代" in df.columns and "目标函数" in df.columns and "狮群" in df.columns:
        data.append(df)

# 合并所有数据
all_data = pd.concat(data, ignore_index=True)

# 筛选迭代次数为100的数据
filtered_data = all_data[all_data["迭代"] == 100]

# 按种群数量分组计算平均值和标准差
stats = filtered_data.groupby("狮群")["目标函数"].agg(["mean", "std"]).reset_index()

# 获取数据用于绘图
x_labels = stats["狮群"]
means = stats["mean"]
std_devs = stats["std"]
print(x_labels)
print(std_devs)
print(means)

width = 6  # 设置柱子的宽度
# 绘制柱状图
plt.figure(figsize=(10, 6))
plt.bar(x_labels[0], means[0], width=width, yerr=std_devs[0], capsize=5, color='#193e8f')
plt.bar(x_labels[1], means[1], width=width, yerr=std_devs[1], capsize=5, color='#55b7e6')
plt.bar(x_labels[2], means[2], width=width, yerr=std_devs[2], capsize=5, color='#004080')
plt.bar(x_labels[3], means[3], width=width, yerr=std_devs[3], capsize=5, color='#FD9F02')
plt.bar(x_labels[4], means[4], width=width, yerr=std_devs[4], capsize=5, color='#A0A0A4')
plt.bar(x_labels[5], means[5], width=width, yerr=std_devs[5], capsize=5, color='#e53528')
plt.bar(x_labels[6], means[6], width=width, yerr=std_devs[6], capsize=5, color='#f8a700')
plt.bar(x_labels[7], means[7], width=width, yerr=std_devs[7], capsize=5, color='#006400')
plt.bar(x_labels[8], means[8], width=width, yerr=std_devs[8], capsize=5, color='#8b008b')
plt.bar(x_labels[9], means[9], width=width, yerr=std_devs[9], capsize=5, color='#9932cc')

# 图形修饰
# plt.title("迭代次数为100时不同种群数量的目标函数", fontsize=16)
plt.xlabel("淘金者数量", fontsize=14)
plt.ylabel("目标函数值", fontsize=14)
plt.xticks(x_labels, fontsize=12)
plt.yticks(fontsize=12)
plt.grid(False)

# 显示每个柱形的具体值
# for bar, mean in zip(bars, means):
#     height = bar.get_height()
#     plt.text(bar.get_x() + bar.get_width() / 2, height + 50, f"{mean:.2f}", ha="center", va="bottom", fontsize=12)
# 设置y轴范围，从2800开始
plt.ylim(2500, 4000)
# 显示图形
plt.tight_layout()
plt.show()
